<template>
  <div class="editor-wrapper">
    <!-- 工具栏 -->
    <el-affix target=".editor-wrapper" :offset="150">
      <Toolbar id="toolbar-container" :editor="editorRef" :default-config="toolbarConfig" :mode="mode" />
    </el-affix>
    <!-- 编辑器 -->
    <Editor
      id="editor-container"
      v-model="modelValue"
      :style="{ height: height + 'px' }"
      :default-config="editorConfig"
      :mode="mode"
      @on-change="handleChange"
      @on-created="handleCreated"
    />
  </div>
  <!-- 文件管理 -->
  <el-dialog
    v-model="fileDialog"
    :title="fileTitle"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    width="80%"
    draggable
    center
    align-center
  >
    <FileManage :file-type="fileType" @file-cancel="fileCancel" @file-submit="fileSubmit" />
  </el-dialog>
</template>

<script setup>
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/store/modules/app'
import { i18nAddResources, i18nChangeLanguage } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import FileManage from '@/components/FileManage/index.vue'

const props = defineProps({
  modelValue: {
    type: [String],
    default: ''
  },
  height: {
    type: [Number],
    default: 500
  }
})

const { t } = useI18n()
const placeholder = t('请输入内容')
const appStore = useAppStore()
const emit = defineEmits(['update:modelValue'])
// 添加新语言
i18nAddResources('es', {
  editor: {
    more: 'Más',
    justify: 'Justificar',
    indent: 'Sangría',
    image: 'Imagen',
    video: 'Video'
  },
  common: { ok: 'Aceptar', delete: 'Eliminar', enter: 'Ingresar' },
  blockQuote: { title: 'Cita' },
  codeBlock: { title: 'Bloque de código' },
  color: {
    color: 'Color de fuente',
    bgColor: 'Color de fondo',
    default: 'Color predeterminado',
    clear: 'Limpiar color de fondo'
  },
  divider: { title: 'Divisor' },
  emotion: { title: 'Emoji' },
  fontSize: { title: 'Tamaño de fuente', default: 'Predeterminado' },
  fontFamily: { title: 'Familia de fuente', default: 'Predeterminado' },
  fullScreen: { title: 'Pantalla completa' },
  header: { title: 'Encabezado', text: 'Texto' },
  image: {
    netImage: 'Imagen de red',
    delete: 'Eliminar imagen',
    edit: 'Editar imagen',
    viewLink: 'Ver enlace',
    src: 'Origen de imagen',
    desc: 'Descripción',
    link: 'Enlace de imagen'
  },
  indent: { decrease: 'Disminuir', increase: 'Aumentar' },
  justify: {
    left: 'Izquierda',
    right: 'Derecha',
    center: 'Centro',
    justify: 'Justificar'
  },
  lineHeight: { title: 'Altura de línea', default: 'Predeterminado' },
  link: {
    insert: 'Insertar enlace',
    text: 'Texto del enlace',
    url: 'URL del enlace',
    unLink: 'Quitar enlace',
    edit: 'Editar enlace',
    view: 'Ver enlace'
  },
  textStyle: {
    bold: 'Negrita',
    clear: 'Limpiar estilos',
    code: 'Código en línea',
    italic: 'Cursiva',
    sub: 'Subíndice',
    sup: 'Superíndice',
    through: 'Tachado',
    underline: 'Subrayado'
  },
  undo: { undo: 'Deshacer', redo: 'Rehacer' },
  todo: { todo: 'Lista de tareas' },
  listModule: {
    unOrderedList: 'Lista desordenada',
    orderedList: 'Lista ordenada'
  },
  tableModule: {
    deleteCol: 'Eliminar columna',
    deleteRow: 'Eliminar fila',
    deleteTable: 'Eliminar tabla',
    widthAuto: 'Ancho automático',
    insertCol: 'Insertar columna',
    insertRow: 'Insertar fila',
    insertTable: 'Insertar tabla',
    header: 'Encabezado'
  },
  videoModule: {
    delete: 'Eliminar',
    uploadVideo: 'Subir video',
    insertVideo: 'Insertar video',
    videoSrc: 'Origen del video',
    videoSrcPlaceHolder: 'URL del archivo de video o <iframe> de terceros',
    videoPoster: 'Póster del video',
    videoPosterPlaceHolder: 'URL de la imagen del póster',
    ok: 'Aceptar',
    editSize: 'Editar tamaño',
    width: 'Ancho',
    height: 'Alto'
  },
  uploadImgModule: {
    uploadImage: 'Subir imagen',
    uploadError: 'Error al subir {{fileName}}'
  },
  highLightModule: { selectLang: 'Idioma' }
})
// 切换语言
i18nChangeLanguage(appStore.getLang('wangeditor'))
const modelValue = useVModel(props, 'modelValue', emit)
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 编辑器模式
const mode = ref('default')
// 工具条配置
const toolbarConfig = ref({
  insertKeys: {
    index: 24, // 自定义插入的位置
    keys: ['uploadAttachment'] // “上传附件”菜单
  },
  excludeKeys: ['fullScreen']
})
// 编辑器配置
const editorConfig = ref({
  placeholder: placeholder,
  MENU_CONF: {
    uploadImage: {
      // 自定义选择图片
      customBrowseAndUpload() {
        fileDialog.value = true
        fileType.value = 'image'
      }
    },
    uploadVideo: {
      // 自定义选择视频
      customBrowseAndUpload() {
        fileDialog.value = true
        fileType.value = 'video'
      }
    },
    uploadAttachment: {
      // 自定义选择附件
      customBrowseAndUpload() {
        fileDialog.value = true
        fileType.value = 'word'
      }
    }
  }
})

const handleCreated = (editor) => {
  // 记录 editor 实例，重要！
  editorRef.value = editor
}

function handleChange(editor) {
  modelValue.value = editor.getHtml()
}

// 文件管理
const fileDialog = ref(false)
const fileTitle = ref('文件管理')
const fileType = ref('image')
function fileCancel() {
  fileDialog.value = false
}
function fileSubmit(files) {
  fileDialog.value = false
  let htmls = ''
  const length = files.length
  for (let i = 0; i < length; i++) {
    if (files[i]['file_type'] === 'image') {
      htmls += `<img file-id="${files[i]['file_id']}" src="${files[i]['file_url']}" style="width:640px;" alt="" />`
    } else if (files[i]['file_type'] === 'video') {
      htmls += `<div data-w-e-type="video" data-w-e-is-void><video width="640" height="480" controls>
                <source file-id="${files[i]['file_id']}" src="${files[i]['file_url']}" type="video/mp4">
                <object file-id="${files[i]['file_id']}" data="${files[i]['file_url']}">
                  <embed file-id="${files[i]['file_id']}" src="${files[i]['file_url']}" width="640" height="480">
                </object>
              </video></div>`
    } else if (files[i]['file_type'] === 'audio') {
      htmls += `<div data-w-e-type="audio" data-w-e-is-void data-w-e-is-inline><audio controls>
                <source file-id="${files[i]['file_id']}" src="${files[i]['file_url']}" type="audio/mp3">
                <embed file-id="${files[i]['file_id']}" src="${files[i]['file_url']}">
              </audio></div>`
    } else {
      htmls += `<div data-w-e-type="attachment" data-w-e-is-void data-w-e-is-inline><a file-id="${files[i]['file_id']}" href="${files[i]['file_url']}" download="${files[i]['file_url']}" target="_blank">${files[i]['file_name']}.${files[i]['file_ext']}</a></div>`
    }
  }
  const editor = editorRef.value
  editor.dangerouslyInsertHtml(htmls)
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.editor-wrapper {
  min-height: 500px;
  border: var(--el-border);
}
</style>
